/*
 * @Author: fanjs
 * @Date: 2025-03-16 22:07:24
 * @Description:
 */
import { forwardRef, useCallback, Key, } from "react";
import {
  Table,
  TableHeader,
  TableColumn,
  TableBody,
  TableRow,
  TableCell,
  Button,
  Chip,
  User,
} from "@heroui/react";
import { formatStatus } from '@/constants/common'
import { deleteRecipientApi } from '@/service/api/email'
import { addToast } from '@heroui/react'

type User = {
  name: string;
  email: string;
  status: string;
  no: number;
  id: string;
  task_id: string;
}

interface ResultTableProps {
  list: User[];
  topContent: React.ReactNode;
  bottomContent: React.ReactNode;
  columns: {
    [key: string]: string;
  };
  refetch: () => void;
}


const ResultTable = forwardRef<any, ResultTableProps>(({ list, topContent, bottomContent, columns, refetch }) => {

  const getColumns = useCallback(() => {
    console.log('🚀 ~ ...Object.entries ~ columns:', columns);
    return [
      { name: "姓名", uid: "name" },
      ...Object.entries(columns).map(([key, value]) => {
        if (key === '邮箱地址') return { name: value || key, uid: 'email' }
        return { name: value || key, uid: value || key }
      }),
      { name: "发件邮箱", uid: "sender" },
      { name: "发送状态", uid: "status", sortable: true },
      { name: "操作", uid: "actions" },
    ];
  }, [columns]);

  const handleDelete = useCallback(async (user: User) => {
    const { data }: any = await deleteRecipientApi({ recipient_id: user.id, task_id: user.task_id })
    if (data) {
      addToast({ title: '删除成功' })
      refetch()
    }
  }, [refetch]);

  const handleEdit = useCallback((user: User) => {
    console.log('🚀 ~ ...Object.entries ~ user:', user);
  }, []);

  // 单元格渲染
  const renderCell = useCallback((user: User, columnKey: Key) => {
    const cellValue = user[columnKey as keyof User];
    switch (columnKey) {
      case "status":
        return (
          <Chip color={formatStatus(user.status)} size="sm" radius="sm" variant="flat">
            {formatStatus(user.status, true)}
          </Chip>
        );
      case "actions":
        return (
          <div className="flex-center">
            <Button size="sm" color="secondary" onPress={() => handleEdit(user)} variant="light">
              编辑
            </Button>
            <Button size="sm" color="danger" onPress={() => handleDelete(user)} variant="light">
              删除
            </Button>
          </div>
        );
      default:
        return cellValue;
    }
  }, [handleDelete, handleEdit]);

  return (
    <Table
      isHeaderSticky
      bottomContent={bottomContent}
      bottomContentPlacement="outside"
      color="secondary"
      classNames={{
        base: "gap-3",
        wrapper: "h-[calc(100vh-246px)]",
      }}
      topContent={topContent}
      topContentPlacement="outside"
    >
      <TableHeader columns={getColumns()}>
        {(column) => (
          <TableColumn
            key={column.uid}
            align={column.uid === "actions" ? "center" : "start"}
            allowsSorting={column.sortable}
          >
            {column.name}
          </TableColumn>
        )}
      </TableHeader>
      <TableBody emptyContent={"当前无数据"} items={list}>
        {(item) => (
          <TableRow key={item.no}>
            {(columnKey) => <TableCell>{renderCell(item, columnKey)}</TableCell>}
          </TableRow>
        )}
      </TableBody>
    </Table>
  );
})

export default ResultTable;
